package top.dotgo.web.admin.oauth.api;

import cn.hutool.core.util.RandomUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import top.dotgo.dao.sys.SysAccountDao;
import top.dotgo.kit.Const;
import top.dotgo.kit.ex.DotMsg;
import top.dotgo.model.shop.ShopStaffEntity;
import top.dotgo.model.shop.dto.ShopStaffDTO;
import top.dotgo.model.sys.SysAccountEntity;
import top.dotgo.model.sys.dto.SysAccountDTO;
import top.dotgo.service.shop.IShopStaffService;
import top.dotgo.service.sys.ISysAccountService;
import top.dotgo.web.base.BaseController;
import top.dotgo.web.base.R;

/**
 * 密码处理接口
 *
 * @author jornl
 * @date 2020/3/12 23:04 星期四
 */
@RestController
@RequestMapping("/passwd")
public class PasswdController extends BaseController {

    private final PasswordEncoder passwordEncoder;

    private final ISysAccountService accountService;
    private final IShopStaffService shopStaffService;

    public PasswdController(PasswordEncoder passwordEncoder, ISysAccountService accountService, IShopStaffService shopStaffService) {
        this.passwordEncoder = passwordEncoder;
        this.accountService = accountService;
        this.shopStaffService = shopStaffService;
    }

    /**
     * 修改密码接口
     *
     * @param old 原始密码
     * @param pwd 新密码
     * @return R.ok
     * @author jornl
     * @date 2020/3/12 23:15
     */
    @PutMapping()
    public R edit(@RequestParam String old, @RequestParam String pwd) {
        SysAccountDTO account = accountService.find(getAccId());
        if (!passwordEncoder.matches(old, account.getPassword())) {
            return R.err(DotMsg.PARAM_ERR, "原始密码错误");
        }
        accountService.updateById(new SysAccountDTO().setAccId(getAccId()).setPassword(passwordEncoder.encode(pwd)));

        return R.ok();
    }

    /**
     * 重置密码
     *
     * @return pwd 新密码
     */
    @DeleteMapping("/reset/{accId}")
    public R reset(@PathVariable Long accId) {
        String pwd = RandomUtil.randomString(6);
        //平台管理员 和 员工可以重置所有人

        if (!getAccType().equals(Const.Type.acc.PT_ADMIN) && getAccType().equals(Const.Type.acc.PT_STAFF)) {
            if (getAccType().equals(Const.Type.acc.SHOP_ADMIN)) {
                long count = shopStaffService.count(new ShopStaffDTO().setCompanyId(getCompanyId()).setAccId(accId));
                if (count <= 0) {
                    return R.err(DotMsg.PARAM_ERR, "重置失败，账号非此公司员工");
                }
            } else if (getAccType().equals(Const.Type.acc.SHOP_STAFF)) {
                return R.err(DotMsg.PARAM_ERR, "普通员工无权重置密码");
            } else if (getAccType().equals(Const.Type.acc.BIZ_USER)) {
                return R.err(DotMsg.PARAM_ERR, "普通用户无权重置密码");
            }
        }

        accountService.updateById(new SysAccountDTO().setAccId(accId).setPassword(passwordEncoder.encode(pwd)));
        return R.ok().put("pwd", pwd);
    }
}
